<?php

namespace app\api\controller\v1\order;

use app\Request;
use app\services\notice\UserNoticeServices;
use app\services\order\TurntableServices;
use app\services\order\TurntableLogServices;


/**
 * 订单控制器
 * Class StoreOrderController
 * @package app\api\controller\order
 */
class TurntableController {

    /**
     * @var TurntableLogServices
     */
    protected $services;

    protected $turntable;

    /**
     * StoreOrderController constructor.
     * @param TurntableLogServices $services
     * @param TurntableServices $turntable
     */
    public function __construct(TurntableLogServices $services, TurntableServices $turntable) {
        $this->services = $services;
        $this->turntable = $turntable;
    }

    public function config()
    {
        $list = $this->turntable->getList();
        shuffle($list);
        return app('json')->successful($list);
    }

    public function getList(Request $request)
    {
        $uid = (int)$request->uid();
        $list = $this->turntable->getList();
        $prize = array_column($list, 'name', 'id');
        $data =  $this->services->getList(['uid' => $uid]);
        foreach ($data as &$datum) {
            $datum['prizeName'] = $prize[$datum['prize']];
        }
        return app('json')->successful($data);
    }

    public function turntable(Request $request)
    {
        $uid = (int)$request->uid();
        $prizes = $this->turntable->getList();
        $worth = array_column($prizes, 'balance', 'id');
        $prizeId = $this->getRand($prizes);
        if ($this->services->turntable($prizeId, $uid, $worth[$prizeId])) {
            return app('json')->successful([
                'prize' => $prizeId,
                'round' => rand(3, 6),
            ]);
        }
        return app('json')->fail('抽奖失败');

    }

    private function getRand($prizes)
    {
        $percents = array_column($prizes, 'percent', 'id');
        $sum = array_sum($percents);

        foreach ($percents as $id => $percent) {
            $rand = mt_rand(1, $sum);
            if ($rand <= $percent) {
                return $id;
            } else {
                $sum -= $percent;
            }
        }
    }

}
